package cn.org.guhao.practice.go.service;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class WordFileGenerator implements Runnable {

  private static final Logger logger = LoggerFactory.getLogger(WordFileGenerator.class);

  private String filename;

  private int index;

  private static List<String> preWords = new ArrayList<String>();
  private String dir = "C:\\Users\\guhao\\Documents\\Projects\\tmp\\";
  static {
    preWords.add("cup");
    preWords.add("pod");
    preWords.add("linux");
    preWords.add("b2c");
    preWords.add("mouse");
    preWords.add("iphone");
    preWords.add("apple");
    preWords.add("laptop");
    preWords.add("qq");
    preWords.add("sleep");
  }

  public WordFileGenerator(String filename,int index) {
    this.filename = filename;
    this.index = index;
  }

  @Override
  public void run() {
    File file = new File(filename);
    if(!file.exists()){
      try {
        file.createNewFile();
      } catch (IOException e) {
        logger.error("创建文件异常", e);
      }
    }
    logger.info("正在写入第[{}]个文件", index+1);
    for(String word:preWords) {
      List<String> writeWords = new ArrayList<String>();
      int count = new Random().nextInt(10000);
      for (int c1 = 0; c1 < count; c1++) {
        writeWords.add(word);
      }
      try {
        FileUtils.writeLines(file,writeWords,true);
      } catch (IOException e) {
        logger.error("写文件异常", e);
      }
      logger.info("第[{}]个文件写入[{}]个[{}]", index+1,count,word);
    }
    List<String> files = new ArrayList<>();
    files.add(file.getPath());
    File listFile = new File(dir+"list.txt");
    try {
      FileUtils.writeLines(listFile,files,true);
    } catch (IOException e) {
      logger.info("文件列表写异常", e);
    }
  }
}
